package framework.utils;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;

/**
 * 版本工具
 */
@Slf4j
@Component
public class VersionUtil {

    @Getter
    private static Date UP_TIME;

    public VersionUtil() {
        UP_TIME = new Date();
    }


    /**
     * 获取jar生成日期, 非jar状态下返回启动时间
     *
     * @return
     */
    public static String jarVersionString(Class cls) {
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.FORMAT_ZONE);
        return sdf.format(jarVersion(cls));
    }

    /**
     * 获取jar生成日期, 非jar状态下返回启动时间
     *
     * @return
     */
    public static Date jarVersion(Class cls) {
//        String version = null;
//        URL resourceURL = cls.getClassLoader().getResource("version.txt");
//        if (resourceURL != null) {
//            try (InputStream inputStream = resourceURL.openStream()) {
//                version = IOUtils.toString(inputStream, "UTF-8");
//            } catch (IOException e) {
//                version = null;
//            }
//        }
//        if (StringUtils.isNotBlank(version)) {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            try {
//                return sdf.parse(version);
//            } catch (ParseException e) {
//                log.error("have set version.txt but format invalid", e);
//            }
//        }

        //
        long time = 0;
        ApplicationHome applicationHome = new ApplicationHome(cls);
        File file = applicationHome.getSource();
        if (file.getName().toLowerCase().endsWith(".jar")) {
            time = file.lastModified();
            Instant instant = Instant.ofEpochMilli(time);
            return Date.from(instant);
        }
        return UP_TIME;
    }
}
